from flask import Blueprint,jsonify,request
from db import db1

from utils.comm import *
users_bp = Blueprint('users',__name__)


def xtree(data):
    list = []
    tree = {}
    if not data:
        return data
    for i in data:
        tree[i['id']] = i
    for j in data:
        pid = j['pid']
        if pid == 0:
            list.append(j)
        else:
        # 查看父类下有没有子类
            if 'son' not in tree[pid]:
                # 如果没有初始化列表
                tree[pid]['son'] = []
            # 把子类加到父类列表中
            tree[pid]['son'].append(j)
    return list


import time
@users_bp.route('/cateM', methods=['POST', 'GET'])
def cateM():
    if request.method == 'POST':
        data = get_data()
        sql = """insert into cates values(0,'%s',%d,%s)""" % (data['name'], int(data['pid']), data['params'])
        db1.update(sql)
        return jsonify({'code': 200})

    elif request.method == 'GET':
        time.sleep(0.001)
        sql = """select * from  cates"""
        res = db1.fid_all(sql)
        data = xtree(res)
        return jsonify({'code': 200, "list": data})

@users_bp.route('/classt',methods=['POST', 'GET'])
def classt():
    if request.method == 'GET':
        sql =  """select * from  teacher"""
        res = db1.fid_all(sql)
        return jsonify({'code': 200,'list':res})

#通过分类id获取分类参数
@users_bp.route('/getCateByid')
def getCateByid():
    id = request.args.get('id')
    sql = "select params from cates where id=%d"%(int(id))
    res = db1.find(sql)
    return jsonify({'code':200,'params':res['params']})


@users_bp.route('/courseM', methods=['POST', 'GET'])
def courseM():
    if request.method == "POST":
        data = get_data()
        if data['params']:
            sql = "insert into courses values(0,'%s',%d,'%s','%s','%s',%d,%d)" % (
            data['title'], int(data['pid']), data['params'], data['pic'], data['descrip'], int(data['teacher_id']),
            int(data['status']))
        else:
            sql = "insert into courses(title,pid,pic,descrip,teacher_id,status) values('%s',%d,'%s','%s',%d,%d)" % (
            data['title'], int(data['pid']), data['pic'], data['descrip'], int(data['teacher_id']), int(data['status']))
        db1.update(sql)
        return jsonify({"code": 200})
    else:
        #获取前端传递当前页
        page = request.args.get('page')
        # 定义每页显示多少条
        page_size = 2
        # 计算开始下标
        start = (int(page)-1)*page_size
        # 查询全部数据
        sql = '''select c.title,c.pic,ca.name from courses as c left join  cates as ca on c.pid=ca.id limit %d,%d'''%(start,page_size)
        res = db1.fid_all(sql)
        # 查询共有多少条
        sql1 = '''select count(id) as count from courses'''
        total = db1.find(sql1)
        return jsonify({"code":200,'list':res,'total':total['count']})


#上传图片
@users_bp.route('/qntoken')
def qntoken():
    time.sleep(0.01)
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = 'zhc6688'
    # 生成上传 Token
    token = q.upload_token(bucket_name)
    return jsonify({"token":token})

# import os
# import uuid
# def upload():
#     #获取文件
#     file = request.files['file']
#     #上传到upload文件夹
#     #解决文件名被覆盖的问题
#     #1.文件重命名   文件名.后缀  1.jpg   asfasfsdf.jpg
#     #获取文件后缀
#     filetext = os.path.splitext(file.filename)[1]
#     newfile = uuid.uuid4().hex+filetext
#     #2.在upload下面建立一个文件夹，专业存，文件夹的名字为userid
#     userid = request.form.get('userid')
#     #根据userid创建文件夹
#     #判断此用户文件夹是否存在，存在直接写文件，不存在创建
#     path = './static/upload/'+str(userid)
#     #不存在创建文件
#     if not os.path.exists(path):
#         os.mkdir(path)
#     file.save(os.path.join(path,newfile))

#视频上传
# @users_bp.route('/vedioUpload',methods=['POST'])
# def vedioUpload():
#     #获取要上传的文件流，课程id
#     file = request.files['file']
#     course_id = request.form['course_id']
#     #判断文件夹是否存在，如果没有，创建文件夹
#     path = './upload/'+str(course_id)
#     if not os.path.exists(path):
#         os.mkdir(path)
#     #上传文件到指定文件夹
#     file.save(os.path.join(path,file.filename))
#     #返回结果
#     return jsonify({"code":200,'url':path+'/'+file.filename})





